//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Sequence.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)

TSequence :: TSequence( TDatabase * db)
{
   qryGet = new TQuery( NULL);
   qryGet->DatabaseName = db->DatabaseName;
   BuildGetQuery();

   qryUpdate = new TQuery( NULL);
   qryUpdate->DatabaseName = db->DatabaseName;
   BuildUpdateQuery();
}

TSequence :: ~TSequence()
{
   delete qryUpdate;
   delete qryGet;
}

void TSequence :: BuildGetQuery()
{
   qryGet->SQL->Add( "SELECT * FROM SEQUENCES WHERE NAME = :NAME");
}

void TSequence :: BuildUpdateQuery()
{
   qryUpdate->SQL->Add( "UPDATE SEQUENCES SET ID = :ID WHERE NAME = :NAME");
}

__int64 TSequence :: GetLastValue( AnsiString name)
{
   __int64 value;

   qryGet->ParamByName( "NAME")->AsString = name;

   qryGet->Open();

   try
   {
      if ( qryGet->IsEmpty())
         value = 1;
      else
         value = qryGet->FieldByName( "ID")->AsInteger;
   }
   __finally
   {
      qryGet->Close();
   }

   return value;
}

__int64 TSequence :: GetNextValue( AnsiString name)
{
   __int64 value;

   try
   {
      value = GetLastValue( name);

      qryUpdate->ParamByName( "ID")->AsInteger = value + 1;
      qryUpdate->ParamByName( "NAME")->AsString = name;
      qryUpdate->ExecSQL();

   }
   __finally
   {
      qryGet->Close();
   }

   return value;
}

